package com.kevin.service;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.nutz.ioc.loader.annotation.IocBean;

import com.kevin.util.DateFormat;
import com.kevin.util.Function;


/**
 * 
  * @ClassName: OutputService 
  * @Description: 输出模块
  * @author 吕凯
  * @date 2012-10-29 上午10:24:17 
  *
 */
@IocBean
public class OutputService {	

	private static final String SPLITSTR = "=-%split%-=";
	@SuppressWarnings("unused")
	private static final String FILEDCONCAT = "%$-%$";
	
	
	/**
	 * 
	  * @方法名  outputExcel 
	  * @功能描述   输出电子表格
	  * @author   吕凯  
	  * @param request
	  * @param response
	  * @param title
	  * @param excelName
	  * @param excelKeyArray
	  * @param dataList
	  * @param showNum
	  * @throws Exception 
	  * @return  void 
	  * @编码时间 2012-10-29 上午10:03:32
	 */
	@SuppressWarnings({ "rawtypes" })
	public void outputExcel(HttpServletRequest request, HttpServletResponse response,String title,String excelName,String[] excelKeyArray,List dataList) throws Exception{
		outputExcel(request, response, title, excelName, excelKeyArray, dataList, true, new HashMap());
	}
	/**
	 * 
	  * @方法名  outputExcel 
	  * @功能描述   输出电子表格
	  * @author   吕凯  
	  * @param request
	  * @param response
	  * @param title
	  * @param excelName
	  * @param excelKeyArray
	  * @param dataList
	  * @param showNum
	  * @throws Exception 
	  * @return  void 
	  * @编码时间 2012-10-29 上午10:03:32
	 */
	@SuppressWarnings({ "rawtypes" })
	public void outputExcel(HttpServletRequest request, HttpServletResponse response,String title,String excelName,String[] excelKeyArray,List dataList,Map formatMap) throws Exception{
		outputExcel(request, response, title, excelName, excelKeyArray, dataList, true,formatMap);
	}
	/**
	 * 
	  * @方法名  outputExcel 
	  * @功能描述   输出电子表格
	  * @author   吕凯  
	  * @param request
	  * @param response
	  * @param title
	  * @param excelName
	  * @param excelKeyArray
	  * @param dataList
	  * @param showNum
	  * @throws Exception 
	  * @return  void 
	  * @编码时间 2012-10-29 上午10:03:32
	 */
	@SuppressWarnings({ "rawtypes"})
	public void outputExcel(HttpServletRequest request, HttpServletResponse response,String title,String excelName,String[] excelKeyArray,List dataList,Boolean showNum) throws Exception{
		outputExcel(request, response, title, excelName, excelKeyArray, dataList, showNum, new HashMap());
	}
	
	/**
	 * 
	  * @方法名  outputExcel 
	  * @功能描述  输出电子表格
	  * @author   吕凯  
	  * @param request
	  * @param response
	  * @param title
	  * @param excelName
	  * @param excelKeyArray
	  * @param dataList
	  * @param showNum
	  * @param formatMap
	  * @throws Exception 
	  * @return  void 
	  * @编码时间 2012-10-29 上午10:02:53
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void outputExcel(HttpServletRequest request, HttpServletResponse response,String title,String excelName,String[] excelKeyArray,List dataList,Boolean showNum,Map formatMap) throws Exception{
		OutputStream os = null; 
		WritableWorkbook wwb = null;
		try {	         
			//设置table列名
	        String[] excelNameArray = excelName.split(",");
//	         
//	         
	        //取得key
//	        String[] excelKeyArray = {"username","gender","age","job","marry","address","hkaddress","fltime","fzpername","type"};
	         
	        os = response.getOutputStream();// 取得输出流   
	        response.reset();// 清空输出流   

	        response.setHeader("Content-disposition", "attachment; filename="+System.currentTimeMillis()+".xls");// 设定输出文件头   
	        response.setContentType("application/msexcel");// 定义输出类型 
     
	        wwb = Workbook.createWorkbook(os);// 建立excel文件   
 
	        WritableSheet ws = wwb.createSheet("Sheet1", 0);// 创建一个工作表

			//设置单元格的文字格式
			WritableFont wf = new WritableFont(WritableFont.ARIAL,12,WritableFont.NO_BOLD,false,
					UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
			WritableCellFormat wcf = new WritableCellFormat(wf);
			wcf.setVerticalAlignment(VerticalAlignment.CENTRE); 
			wcf.setAlignment(Alignment.CENTRE); 
			ws.setRowView(0, 500);
		
			WritableFont wf_merge = new WritableFont(WritableFont.ARIAL,12,WritableFont.BOLD,false,
					UnderlineStyle.DOUBLE_ACCOUNTING,jxl.format.Colour.GREEN);
			WritableCellFormat wff_merge = new WritableCellFormat(wf_merge);
			wff_merge.setVerticalAlignment(VerticalAlignment.CENTRE); 
			wff_merge.setAlignment(Alignment.CENTRE); 
		
		     //设置标题
			ws.addCell(new Label(0, 0, title, wff_merge));
			if(showNum){
				ws.mergeCells(0,0,excelKeyArray.length,0);//增加序号列
			} else {
				ws.mergeCells(0,0,excelKeyArray.length-1,0);//不增加序号列
			}
		     
			//设置列头名
			for (int j=0;j<excelNameArray.length;j++){
				if(showNum && excelNameArray.length<=excelKeyArray.length){
					if(j==0){
						ws.addCell(new Label(j, 1, "序号", wcf));
						ws.addCell(new Label(j+1, 1, excelNameArray[j], wcf));
					}else{
						ws.addCell(new Label(j+1, 1, excelNameArray[j], wcf));
					}
				}else{
					ws.addCell(new Label(j, 1, excelNameArray[j], wcf));
		        	
				}
			}
		     //设置内容
		//	         wcf = new WritableCellFormat();
		//	         wcf.setVerticalAlignment(VerticalAlignment.CENTRE); 
		//             wcf.setAlignment(Alignment.CENTRE);
			if(dataList != null && !dataList.isEmpty()){//s数据循环
				for(int i=1;i<dataList.size();i++){	
					Object obj = dataList.get(i);
					if(showNum)
						ws.addCell(new Label(0, i+1, i+"", wcf));
					for (int j=0;j<excelKeyArray.length;j++){//变量循环
						String value = "";
		    			 
						Pattern pattern = Pattern.compile("(%\\$(.*?)%\\$)");
						Matcher matcher = pattern.matcher(excelKeyArray[j]);
							
				    	List splitKey = new ArrayList();
				    	String excelKey = excelKeyArray[j];
						while(matcher.find()){
							excelKey = excelKey.replace(matcher.group(0), SPLITSTR);
							splitKey.add(matcher.group(2)+"");
						}
						
						if(excelKey.contains(SPLITSTR)){
							String[] excelKeyss = excelKey.split(SPLITSTR);
							for(int k=0;k<excelKeyss.length;k++){
								if(excelKeyss[k].length() > 0)
									value += getValue(obj, excelKeyss[k], j, formatMap)+"";
								if(splitKey.size() >k){
									value += splitKey.get(k);
								}
							}
						}else {
							value = getValue(obj, excelKey, j , formatMap)+"";
						}
		    			 
		    			 int c = j+1;
		    			 if(!showNum){	
		    				 c = j;
		    			 }
		    			 ws.addCell(new Label(c, i+1, value, wcf));
		             }
		    	 }
		     }
		     wwb.write();
		     System.out.println("export >>>> exl");
		} catch (Exception e){
			e.printStackTrace();
		}finally{
		 try {
			 if(wwb != null)
				 wwb.close();
		 } catch (WriteException e) {e.printStackTrace();}
		 os.close();
		}
	}
	/**
	 * 
	  * @方法名  getValue 
	  * @功能描述  获取属性值
	  * @author   吕凯  
	  * @param obj
	  * @param key
	  * @param index
	  * @param formatMap
	  * @return
	  * @throws Exception 
	  * @return  String 
	  * @编码时间 2012-10-29 上午10:01:46
	 */
	@SuppressWarnings("rawtypes")
	public String getValue(Object obj,String key,int index,Map formatMap) throws Exception{
		String value = "";
		Object o = obj;
		if(key != null && !"".equals(key)) {
			//多级属性
			if(key.contains(".")){
				String[] keys = key.split("\\.");
				for(int i=0;i<keys.length-1;i++){
					o = Function.getValue(o, keys[i]);
					key = keys[i+1];
				}
			}
			try {
				value = Function.getValue(o, key)+"";
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(value.equals("null")){
				value = " ";
			}
		} else {
			value = " ";
		}
		if(formatMap.get(index) != null){
			Object[] objArray = (Object[])formatMap.get(index);
			String type = (String)objArray[0];
			Object objValue = objArray[1];
			if(objValue instanceof List){
				List objValueList = (ArrayList)objValue;
				//格式化日期
				if("date".equals(type)){
					Date dateValue = (Date)Function.getValue(obj, key);
					value = DateFormat.formatDate(dateValue, (String)objValueList.get(0)); 
				}
			}else if(objValue instanceof Map){
				Map objValueMap = (Map)objValue;
				//格式化 固定类型 如性别0男1女 
				if("switch".equals(type)){
					if(objValueMap.containsKey(value))
						value = (String)objValueMap.get(value);
				}
			}
		}
		return value;
	}
	
}
